<?php

namespace app\api\controller;

use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class Ak extends Base
{
  /**
   * 凭证服务器列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'platform' => input('param.platform', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    if (!empty($data['platform'])) {
      $where[] = ['platform', 'like', $data['platform']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('ak_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('ak_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['limit_server_ip'] = (isset($vo['limit_server_ip']) && !empty($vo['limit_server_ip']))?explode(',', $vo['limit_server_ip']):[];
      switch ($vo['platform']) {
        case 'aliyun':
          $vo['platform_title'] = '阿里云';
          break;
        case 'tencent':
          $vo['platform_title'] = '腾讯云';
          break;
        case 'huawei':
          $vo['platform_title'] = '华为云';
          break;
        case 'qiniu':
          $vo['platform_title'] = '七牛云';
          break;
        case 'smsbao':
          $vo['platform_title'] = '短信宝';
          break;
        case 'jdcloud':
          $vo['platform_title'] = '京东云';
          break;
        default:
          $vo['platform_title'] = '未知';
          break;
      }
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_ak_list()
  {
    $where['uid'] = $this->uid;
    $where['status'] = 1;
    $platform = input('param.platform','','trim');
    $title = input('param.title','','trim');
    if (!empty($platform)) {
      if ($platform == 'aliyun_oss' || $platform == 'aliyun') {
        $where['platform'] = 'aliyun';
      }elseif ($platform == 'tencent' || $platform == 'tencent_cos') {
        $where['platform'] = 'tencent';
      }else {
        $where['platform'] = $platform;
      }
    }
    if (!empty($title)) {
      $dataList = Db::connect('mongodb')->name('ak_list')->field('_id,title')->where($where)->whereLike('title',$title)->order('create_time', 'desc')->limit(10)->select()->toArray();
    }else{
      $dataList = Db::connect('mongodb')->name('ak_list')->field('_id,title')->where($where)->order('create_time', 'desc')->limit(10)->select()->toArray();
    }
    return Result::Success($dataList);
  }
  public function edit_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'max:128',
        'platform|凭证平台'  => 'require',
        'status|配置状态'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'platform' => input('param.platform', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'is_ip_limit' => input('param.is_ip_limit', 0, 'trim'),
        'limit_server_ip' => input('param.limit_server_ip', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'aliyun_key_id' => input('param.aliyun_key_id', '', 'trim'),
        'aliyun_key_secret' => input('param.aliyun_key_secret', '', 'trim'),
        'tenc_secret_id' => input('param.tenc_secret_id', '', 'trim'),
        'tenc_secret_key' => input('param.tenc_secret_key', '', 'trim'),
        'huawei_app_key' => input('param.huawei_app_key', '', 'trim'),
        'huawei_app_secret' => input('param.huawei_app_secret', '', 'trim'),
        'qiniu_ak' => input('param.qiniu_ak', '', 'trim'),
        'qiniu_sk' => input('param.qiniu_sk', '', 'trim'),
        'geetest_id' => input('param.geetest_id', '', 'trim'),
        'geetest_key' => input('param.geetest_key', '', 'trim'),
        'jdcloud_access_key_id' => input('param.jdcloud_access_key_id', '', 'trim'),
        'jdcloud_access_key_secret' => input('param.jdcloud_access_key_secret', '', 'trim'),
        'smsbao_username' => input('param.smsbao_username', '', 'trim'),
        'smsbao_password' => input('param.smsbao_password', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['is_ip_limit'] = (int) $data['is_ip_limit'];
      $data['limit_server_ip'] = !empty($data['limit_server_ip'])?implode(',', $data['limit_server_ip']):'';
      $limitCount = Db::connect('mongodb')->name('ak_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'ak_num', '凭证配置数量', $limitCount);
      $data['status'] = intval($data['status']);
      $this->redis->del('dever:ak:'.$data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('ak_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('AK');
        $status = Db::connect('mongodb')->name('ak_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('ak_list')->where('_id', $id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function del()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $this->redis->del('dever:ak:' . $data['id'], 'full');
    $status = Db::connect('mongodb')->name('ak_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    foreach ($data['id'] as $key) {
      $this->redis->del('dever:ak:' . $key, 'full');
    }
    $status = Db::connect('mongodb')->name('ak_list')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
}
